package com.dlc.beijingrfid.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.OnClick;
import com.dlc.beijingrfid.R;
import com.dlc.beijingrfid.adapter.LaundryAdapter;
import com.dlc.beijingrfid.base.BaseActivity;
import com.dlc.beijingrfid.helper.DBManager;
import com.dlc.beijingrfid.net.bean.HotelRfidBean;
import com.dlc.beijingrfid.net.bean.OrderDetailBean;
import com.dlc.beijingrfid.net.bean.RFIDSpecListBean;
import com.dlc.beijingrfid.net.bean.WashBean;
import com.dlc.beijingrfid.net.exception.ErrorMsgException;
import com.dlc.beijingrfid.net.protocol.StockProto;
import com.dlc.beijingrfid.net.protocol.base.HttpProtocol;
import com.dlc.commonlibrary.ble.RfidHelper;
import com.dlc.commonlibrary.dialog.SureDialog;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.utils.ToastUtil;
import com.dlc.commonlibrary.widget.TitleBar;
import java.util.ArrayList;
import java.util.List;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/7/19 0019.
 */

public class ChuKuActivity extends BaseActivity {

    @BindView(R.id.titleBar)
    TitleBar titleBar;
    @BindView(R.id.order_number)
    TextView mOrderNumber;
    @BindView(R.id.hotel)
    TextView mHotel;
    @BindView(R.id.pro_name)
    TextView mProName;
    @BindView(R.id.classify)
    TextView mClassify;
    @BindView(R.id.pro_count)
    TextView mProCount;
    @BindView(R.id.check)
    Button mCheck;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;

    private Handler mHandler;
    private LaundryAdapter mLaundryAdapter;

    private ArrayList<String> rfids = new ArrayList<>();
    private String pagesize = "10000";
    private DBManager dbManager = DBManager.getInstance(this);
    private ArrayList<String> saveList = new ArrayList<>();//在数据库中保存的RFID
    List<String> SumList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titleBar.leftImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleBar.titleText.setText("送洗出库");
        mHandler = new Handler();
        rfids = getIntent().getStringArrayListExtra("rfids");

        // 查询送货单详情
        initRecyclerView();
        getDbData();
        savaDb(rfids);
    }
    /**
     * 获取数据库的数据
     */
    private void getDbData(){
        List<HotelRfidBean> list = dbManager.queryLabelListHotel();
        for (HotelRfidBean bean:list){
            saveList.add(bean.getRfid());
        }
        if (saveList.size() > 0){
            LogPlus.e(saveList.toString());
            if (rfids != null) {
                SumList.addAll(rfids);
            }
            SumList.addAll(saveList);
            SumList = RfidHelper.removeDuplicateWithOrder(SumList);
            ToastUtil.show(ChuKuActivity.this ,"存在未提交数据");

        }else {
            if (rfids != null) {
                SumList.addAll(rfids);
            }
        }
        mOrderNumber.setText(String.valueOf(SumList.size()));
        queryOrderDetail();

    }

    private void isSaveData(){
        if (rfids.size() > 0) {
            SureDialog sureDialog = new SureDialog(ChuKuActivity.this, "是否确定保存数据");
            sureDialog.setOnCallBackListener(new SureDialog.OnCallBack() {
                @Override
                public void sure() {
                    //Intent intent = new Intent();
                    //intent.putStringArrayListExtra("rfid",rfids);
                    //setResult(RESULT_OK, intent); //intent为A传来的带有Bundle的intent，当然也可以自己定义新的Bundle
                    savaDb(rfids);
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    },2000);

                }

                @Override
                public void cancle() {
                    finish();
                }
            });
        }else {
            finish();
        }
    }
    private void savaDb(ArrayList<String> list){
        long timeStamp = System.currentTimeMillis();
        for (String string:list){
            HotelRfidBean bean = new HotelRfidBean(null,string,timeStamp);
            dbManager.insertLabel(bean);
        }
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_chuku_hotel;
    }

    private void initRecyclerView(){
        mLaundryAdapter = new LaundryAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mLaundryAdapter);
    }

    /**
     * 查询订单详情
     */
    private void queryOrderDetail() {
        String rfid ="" ;
        for (int i= 0; i < SumList.size();i++){
            rfid = rfid + SumList.get(i)+",";
        }
        if(!TextUtils.isEmpty(rfid))
            rfid = rfid.substring(0,rfid.length()-1);
        else {
            rfid = "-1";
        }
        mOrderNumber.setText(String.valueOf(SumList.size()));
        StockProto.get().rfid_spec(rfid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RFIDSpecListBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        showOneToast(e.getMessage());
                    }

                    @Override
                    public void onNext(RFIDSpecListBean dataBean) {
                        mLaundryAdapter.setNewData(dataBean.data);

                    }
                });
    }

    private void commitData() {
        String rfid ="" ;
        for (int i= 0; i < SumList.size();i++){
            rfid = rfid + SumList.get(i)+",";
        }
        if(!TextUtils.isEmpty(rfid))
            rfid = rfid.substring(0,rfid.length()-1);
        else {
            rfid = "-1";
        }
       // String hotel_id = UserHelper.get().gethotel_id();
        StockProto.get().order_wash_new(rfid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<WashBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        showOneToast(e.getMessage());
                    }

                    @Override
                    public void onNext(WashBean dataBean) {
                        dbManager.deleteLabelAll();
                        showOneToast(dataBean.msg);
                        getDetailData(dataBean.data.order_id+"");
                    }
                });
    }

    private void getDetailData(String id) {
        StockProto.get()
            .getOrderDetail("order_wash_detail", id, new HttpProtocol.Callback<OrderDetailBean>() {
                @Override
                public void onSuccess(OrderDetailBean orderDetailBean) {
                    dismissLoadingDialog();
                    Toast.makeText(getActivity(), orderDetailBean.msg, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(getActivity(), OrderDetailActivity1.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("detailData", orderDetailBean);
                    intent.putExtras(bundle);
                    intent.putExtra("type", 0);
                    startActivity(intent);
                }

                @Override
                public void onFailed(int code, ErrorMsgException e) {
                    Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    dismissLoadingDialog();
                }
            });
    }

    @OnClick({R.id.check})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.check:
                SureDialog sureDialog = new SureDialog(ChuKuActivity.this,"全部读取完成，确认提交");
                sureDialog.setOnCallBackListener(new SureDialog.OnCallBack() {
                    @Override
                    public void sure() {
                        commitData();
                    }

                    @Override
                    public void cancle() {

                    }
                });
                break;
        }
    }

}



